package com.heima.aliyun.green.config;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.green.model.v20180509.TextScanRequest;
import com.aliyuncs.http.FormatType;
import com.aliyuncs.http.HttpResponse;
import com.aliyuncs.profile.DefaultProfile;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.*;

@Slf4j
public class TextGreenScan {

    @Autowired
    private AliyunProperties aliyunProperties;

    /*****
     * 1、秘钥和应用ID抽取出去
     * 2、需要检测的内容，作为方法入参
     * 3、检测的结果用Map<String,String> 返回
     * 抽取文本检测
     */
    public Map<String,String> textGreenScan(String content) throws Exception {
        //1、创建client对象
        DefaultProfile profile = DefaultProfile.getProfile(
                "cn-shanghai",
                aliyunProperties.getAccessKey(),
                aliyunProperties.getSecret());
        DefaultProfile.addEndpoint("cn-shanghai", "Green", "green.cn-shanghai.aliyuncs.com");
        IAcsClient client = new DefaultAcsClient(profile);

        //2、Http提交方式及属性封装
        TextScanRequest textScanRequest = new TextScanRequest();
        textScanRequest.setAcceptFormat(FormatType.JSON); // 指定API返回格式。
        textScanRequest.setHttpContentType(FormatType.JSON);
        textScanRequest.setMethod(com.aliyuncs.http.MethodType.POST); // 指定请求方法。
        textScanRequest.setEncoding("UTF-8");
        textScanRequest.setRegionId("cn-shanghai");

        //3、封装检测对象JSON数组
        List<Map<String, Object>> tasks = new ArrayList<Map<String, Object>>();

        //3.1 封装的待检测的单个内容
        Map<String, Object> task1 = new LinkedHashMap<String, Object>();
        task1.put("dataId", UUID.randomUUID().toString());
        task1.put("content", content);  //待检测的文本，长度不超过10000个字符。

        //3.2 将被捡的对象存入到tasks集合中
        tasks.add(task1);

        //4、封装JSON对象【远程请求的参数封装】
        JSONObject data = new JSONObject();
        data.put("scenes", Arrays.asList("antispam"));  //检测场景。文本垃圾检测请传递antispam。
        data.put("tasks", tasks);   //要检测的多个对象
        textScanRequest.setHttpContent(data.toJSONString().getBytes("UTF-8"), "UTF-8", FormatType.JSON);

        //4.1 请务必设置超时时间。
        textScanRequest.setConnectTimeout(3000);
        textScanRequest.setReadTimeout(6000);

        //5、发送远程请求
        try {
            HttpResponse httpResponse = client.doAction(textScanRequest);
            if (!httpResponse.isSuccess()) {
                log.error("请求失败，状态码：{}",httpResponse.getStatus());
                throw new RuntimeException("请求失败，状态码："+httpResponse.getStatus());
            }
            JSONObject scrResponse = JSON.parseObject(new String(httpResponse.getHttpContent(), "UTF-8"));

            //获取状态码=200
            if (200 != scrResponse.getInteger("code")) {
                log.error("检测失败，状态码：{}",scrResponse.getInteger("code"));
                throw new RuntimeException("检测失败，状态码："+scrResponse.getInteger("code"));
            }

            //获取检测的结果
            Map<String,String> resultMap = new HashMap<>();
            JSONArray taskResults = scrResponse.getJSONArray("data");
            for (Object taskResult : taskResults) {
                //处理解析的状态码
                if (200 != ((JSONObject) taskResult).getInteger("code")) {
                    log.error("任务解析失败，状态码:{}",((JSONObject) taskResult).getInteger("code"));
                    continue;
                }

                //解析结果集
                JSONArray sceneResults = ((JSONObject) taskResult).getJSONArray("results");
                for (Object sceneResult : sceneResults) {
                    //检测的场景
                    String scene = ((JSONObject) sceneResult).getString("scene");
                    //检测的结果
                    String suggestion = ((JSONObject) sceneResult).getString("suggestion");
                    //垃圾类型
                    String label = ((JSONObject) sceneResult).getString("label");

                    resultMap.put("suggestion",suggestion);
                    resultMap.put("label",label);
                    resultMap.put("scene",scene);
                }
            }

            log.info("审核结果：{}",resultMap);
            return resultMap;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
